package com.example.downloader.upload;

import android.support.v4.util.SparseArrayCompat;

import java.util.LinkedHashMap;
import java.util.Map;

class TaskQueue<R> {
    private final Map<String, Task<R>> mTaskQueue = new LinkedHashMap<>();
    private final SparseArrayCompat<Callback<R>> mTaskCallbacks = new SparseArrayCompat<>();

    void pushNewTask(Task<R> task, Callback<R> callback) {

        if (callback != null) {
            mTaskCallbacks.append(callback.getId(), callback);
        }
        mTaskQueue.put(task.getPath(), task);
    }

    void addTaskCallback(Callback<R> callback) {
        mTaskCallbacks.append(callback.getId(), callback);
    }


//    void recordTaskCallback(Callback<R> callback) {
//        mTaskCallbacks.append(callback.getId(), callback);
//    }


    Callback<R> popTaskCallback(int id) {
        final int index = mTaskCallbacks.indexOfKey(id);
        if (index >= 0) {
            final Callback<R> callback = mTaskCallbacks.valueAt(index);
            mTaskCallbacks.removeAt(index);
            return callback;
        }
        return null;
    }

    Task<R> getTask(String path) {
        return mTaskQueue.get(path);
    }

    Task<R> popTask(String path) {
        return mTaskQueue.remove(path);
    }

    Map<String, Task<R>> getTasks() {
        return mTaskQueue;
    }


//    public void releaseCallback(int id) {
//        final Callback<R> callback = popTaskCallback(id);
//        if (callback != null) {
//            final Task<R> task = callback.getTask();
//            if (task != null) {
//                task.removeCallback(callback);
//                callback.detachTask();
//            }
//        }
//
//    }


}
